<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of "myWiWall".
# Copyright (c) 2007-2008 CRP Henri Tudor and contributors.
# All rights reserved.
#
# "myWiWall" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
# 
# "myWiWall" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with "myWiWall"; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ***** END LICENSE BLOCK *****


/**
 * The Util class gathers the utility functions of the MyWiWall software. If you are
 * a developper, feel free to add new utility functions (shared or not by different
 * packages) in this class as static methods.
 *
 * @package mywiwall.util
 * @author Laurent Haan <laurent.haan@gmail.com>
 * @author J�r�me Bogaerts <jerome.bogaerts@gmail.com>
 */
class Util
{
	/**
	 *
 	 * this function is used to fully remove a directory and all of its subfolders,
 	 * similar to the Unix "rm -fr" command.
	 *
	 * @param string $dirname The path of the directory to remove.
	 * @return boolean Returns true if the deletion has been completed, false if not.
	 */
	public static function full_rmdir($dirname)
	{
        if ($dirHandle = opendir($dirname))
        {
            $old_cwd = getcwd();
            chdir($dirname);

            while(false!==($file=readdir($dirHandle)))
            {
                if ($file == '.' || $file == '..') continue;

                if (is_dir($file))
                {
                    if (!@Util::full_rmdir($file)) return false;
                }
                else
                {
                    if (!unlink($file)) return false;
                }
            }

            closedir($dirHandle);
            chdir($old_cwd);
            if (!rmdir($dirname)) return false;

            return true;
        }
        else
        {
            return false;
        }
    }
    
    /**
     * This utility method provides you the possibility to get
     * the Module/Action (see PHPFramework) relevant to a given
     * string (referer). This string must be 'wall' or 'admin'
     * or 'subscribe'.
     * 
     * For instance, if you provide the 'wall' string to this method,
     * it will return 'wall/index'.
     *
     * @param string $referer The string you want the relevant Module/Action link.
     * @return string Returns you the relevant Module/Action link. If the $referer parameter is unknown, it will return 'wall/index'.
     */
    public static function getActionString($referer)
    {
    	switch ($referer)
    	{
    		case 'wall':
    			return 'wall/index';
    			break;
    			
    		case 'admin':
    			return 'admin/index';
    			break;
    			
    		case 'subscribe':
    			return 'subscribing/subscribe';
    			break;
    			
    		default:
    			return 'wall/index';
    	}
    }
    
    /**
     * Find a file's mime type (only 'text/plain' or 'application/x-zip'). If the file
     * does not fit to these type, this function returns null.
     *
     * @param string $file The path of the file you need to know the type.
     * @return string The file type.
     */
    public static function validateFileType($file)
    {
    	// FIXME Improve file recognition. For instance we could try to use other information than the extension ...
    	if (eregi('\.zip$', $file))
	    	return 'application/x-zip';
	    	
	    else if (eregi('\.xml$', $file))
	    	return 'text/plain';
	    	
	    else
	    	return null;
    }
    
    public static function getDirectoryContentNames($dirPath, array $filter)
    {
	    $fileNames = array();
		$dir = opendir($dirPath);
		
		while (false !== ($fname = readdir($dir)))
		{
			if ($fname != '.' && $fname != '..' && !in_array($fname, $filter))
				$fileNames[] = $fname;
		}
		
		return $fileNames;
    }
    
    public static function checkUserIdentifiers($username, $md5Password)
    {
    	$db = DbUtil::accessFactory();
    	$username = $db->escape($username);
    	$md5Password = $db->escape($md5Password);
    	
    	$rs = $db->select("SELECT username FROM users WHERE username = '${username}' && password = '${md5Password}'");
    	
    	return $rs->count();
    }
    
    public static function checkPasswordLength($password)
    {
    	return strlen($password) >= PASSWORDS_MIN_LENGTH;
    }
    
    public static function getAvailableLanguages()
    {
    	$lgs 	= self::getDirectoryContentNames(dirname(__FILE__) . '/../../locales', array('.svn'));
    	$a 		= array();
    	
    	foreach ($lgs as $lg)
    	{
    		include (dirname(__FILE__) . "/../../locales/${lg}/manifest.php");
    		$a[$lg] = $lang_label;
    	}
    	
    	return $a;
    }
    
    public static function getAvailableUserTypes()
    {
    	return array ('Simple user' => 0,
    				  'Administrator' => 2);	
    }
    
    public static function isUsernameValid($username)
    {
    	if (count($GLOBALS['USERNAME_FORBIDDEN_CHARS']) == 0)
    		return true;
    	
    	$pattern = '';

    	foreach ($GLOBALS['USERNAME_FORBIDDEN_CHARS'] as $char)
    		$pattern .= ($char.'|'); 
    		
    	$pattern = substr($pattern, 0, strlen($pattern) - 1);
   
    	return !eregi($pattern, $username);
    }
    
    public static function getForbiddenCharsAsString()
    {
    	return implode('', $GLOBALS['USERNAME_FORBIDDEN_CHARS']);
    }
    
    public static function buildAddEditUserErrorMessage(UsersManagementException $e)
    {
    	$message = '';
		
		switch ($e->getCode())
		{
			case UsersManagementException::PASSWORD_EMPTY:
				$message = __("Please provide a password.");
			break;
			
			case UsersManagementException::PASSWORD_TOO_SHORT:
				$message = sprintf(__("The password is too short and must be composed of at least %s characters."), PASSWORDS_MIN_LENGTH);
			break;
			
			case UsersManagementException::USERNAME_EMPTY:
				$message = __("Please provide a username.");
			break;
			
			case UsersManagementException::USERNAME_TOO_SHORT:
				$message = sprintf(__("The username is too short and must be composed of at least %s characters."), USERNAME_MIN_LENGTH);
			break;
			
			case UsersManagementException::USERNAME_TOO_LONG:
				$message = sprintf(__("The username is too long and cannot exceed %s characters."), USERNAME_MAX_LENGTH);
			break;
			
			case UsersManagementException::USERNAME_CHARS_FORBIDDEN:
				$message = sprintf(__("The username contains forbidden characters."));
			break;
			
			case UsersManagementException::USERNAME_ALREADY_IN_USE:
				$message = __("Username already in use.");
			break;
			
			case UsersManagementException::PASSWORDS_DIFFERENT:
				$message = __("The provided passwords are different. Please try again.");
			break;
		}
		
		return $message;
    }
}
?>